import { defineStore } from "pinia";
import { computed, ref, onUnmounted } from "vue";
import useLiveDataStore from "./LiveDataStore";

const useLiveCountdown = defineStore("countdown", () => {
  const store = useLiveDataStore();
  const initialDate = computed(() => {
    if (store.roomData) {
      return new Date(store.roomData.streamStartTime);
    }
    return null;
  });
  const remainingTime = ref(0);
  const isCountdownFinished = ref(false);
  let animationFrameId: number | null = null;
  let lastTime = 0;

  // 格式化显示
  const formattedDays = computed(() =>
    Math.floor(remainingTime.value / (1000 * 3600 * 24))
      .toString()
      .padStart(2, "0")
  );

  const formattedHours = computed(() =>
    Math.floor((remainingTime.value % (1000 * 3600 * 24)) / (1000 * 3600))
      .toString()
      .padStart(2, "0")
  );

  const formattedMinutes = computed(() =>
    Math.floor((remainingTime.value % (1000 * 3600)) / (1000 * 60))
      .toString()
      .padStart(2, "0")
  );

  const formattedSeconds = computed(() =>
    Math.floor((remainingTime.value % (1000 * 60)) / 1000)
      .toString()
      .padStart(2, "0")
  );

  // 开始时间显示
  const startTime = computed(() => {
    const date = initialDate.value;
    if (!date) {
      return "";
    }
    return `${date.getFullYear()}-${(date.getMonth() + 1)
      .toString()
      .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
      .getHours()
      .toString()
      .padStart(2, "0")}:${date
      .getMinutes()
      .toString()
      .padStart(2, "0")}:${date.getSeconds().toString().padStart(2, "0")}`;
  });

  // 检查倒计时状态
  const checkCountdownStatus = () => {
    if (!initialDate.value) return;

    const now = Date.now();
    remainingTime.value = Math.max(initialDate.value.getTime() - now, 0);

    // 如果初始时就已经结束，直接设置状态
    if (remainingTime.value === 0) {
      isCountdownFinished.value = true;
      return true;
    }
    return false;
  };

  // 倒计时更新逻辑
  const updateRemaining = (timestamp: number) => {
    if (!initialDate.value) {
      return;
    }

    // 控制更新频率为 1s
    if (timestamp - lastTime >= 1000) {
      const now = Date.now();
      remainingTime.value = Math.max(initialDate.value.getTime() - now, 0);
      lastTime = timestamp;

      // 检查倒计时是否结束
      if (remainingTime.value === 0) {
        isCountdownFinished.value = true;
        stopTimer();
        return;
      }
    }

    // 继续动画
    animationFrameId = requestAnimationFrame(updateRemaining);
  };

  // 启动倒计时
  const startTimer = () => {
    // 停止可能存在的动画
    if (animationFrameId) {
      cancelAnimationFrame(animationFrameId);
    }
    // 重置时间戳
    lastTime = 0;
    // 启动动画
    animationFrameId = requestAnimationFrame(updateRemaining);
  };

  // 停止倒计时
  const stopTimer = () => {
    if (animationFrameId) {
      cancelAnimationFrame(animationFrameId);
      animationFrameId = null;
    }
  };

  // 重置倒计时
  const resetTimer = () => {
    stopTimer();
    remainingTime.value = 0;
    lastTime = 0;
    isCountdownFinished.value = false;
  };

  // 组件卸载时清理
  onUnmounted(() => {
    stopTimer();
  });

  return {
    formattedDays,
    formattedHours,
    formattedMinutes,
    formattedSeconds,
    startTime,
    remainingTime,
    isCountdownFinished,
    checkCountdownStatus,
    startTimer,
    stopTimer,
    resetTimer
  };
});

export default useLiveCountdown;
